

    var map = new AMap.Map("container", {
        zoom: 5,
        //center: [116.412427, 39.303573],
        pitch: 0,
        viewMode: '2D',
    });

function getAllCoordinates(result) {
    // 初始化一个空数组来存储所有坐标
    const allCoordinates = [];
  
    // 遍历每条路线
    result.routes.forEach((route) => {
      // 遍历路线中的每个步骤
      route.steps.forEach((step) => {
        // 将步骤中的每个坐标添加到总数组中
        step.path.forEach((coord) => {
          // 使用 getLng() 和 getLat() 方法从 LngLat 对象获取经纬度
          const longitude = coord.getLng();
          const latitude = coord.getLat();
          allCoordinates.push([longitude, latitude]);
          //console.log(longitude,latitude)
        });
      });
    });
  
    // 返回包含所有坐标的数组
    return allCoordinates;
  }
  // 绘制轨迹
  

  // 使用示例（假设 drivingResult 是有效的 DrivingResult 对象）
 
  // 根据起终点名称规划驾车导航路线

    function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      }
  function doSearch(locations){
    var marker, lineArr=[];
    var randomColor = getRandomColor();
    var driving = new AMap.Driving({
        map: map,
        outlineColor:randomColor
        //panel: "panel"
    }); 
    /*var polyline = new AMap.Polyline({
        map: map,
        path: lineArr,
        showDir:true,
        strokeColor: "#28F",  //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6,      //线宽
        // strokeStyle: "solid"  //线样式
    });*/
    
    var passedPolyline = new AMap.Polyline({
        map: map,
        // path: lineArr,
        strokeColor: "#AF5",  //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6,      //线宽
        // strokeStyle: "solid"  //线样式
    });
    
    driving.search(locations, function(status, result) {
        // result 即是对应的驾车导航信息
        if (status === 'complete') {
            log.success('绘制驾车路线完成')
            lineArr = getAllCoordinates(result)
            marker = new AMap.Marker({
              map: map,
              //position: [116.478935,39.997761],
              icon: "../css/truck.png",
              offset: new AMap.Pixel(-26, -13),
              autoRotation: true,
              angle:-90,
          });
      
          
      
          marker.on('moving', function (e) {
              passedPolyline.setPath(e.passedPath);
          });
      
          //map.setFitView();
          marker.moveAlong(lineArr, 1000000);
            //console.log(lineArr)
        } else {
            log.error('获取驾车数据失败：' + result)
        }
    });
  
      console.log(lineArr);
  }

//doSearch(locationData);//路径和动画绘制
var geocoder = new AMap.Geocoder();

// 存储转换后的坐标
var coordinates = [];

// 转换地点名称为坐标，并存储在数组中
function convertLocationsToCoordinates(locations) {
  
    locations.forEach(function(location, index) {
        geocoder.getLocation(location.keyword, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                coordinates.push(result.geocodes[0].location);
                if (index === locations.length - 1) {
                    // 所有地点转换完成后，绘制飞行轨迹
                    drawFlightPath(coordinates);
                    marker=createPlaneMarker(map, coordinates[0], "../css/plane.png");
                    marker.on('moving', function (e) {
                      //passedPolyline.setPath(e.passedPath);
                    });
              
                  //map.setFitView();
                    marker.moveAlong(coordinates, 1000000);
                }
            } else {
                console.error('地点查询失败', location.keyword, result);
            }
        });
    });
}

// 绘制飞行轨迹
function drawFlightPath(path) {
    // 绘制折线
    var polyline = new AMap.Polyline({
        map: map,
        path: path,
        strokeColor: "#FF0000", // 轨迹颜色
        strokeWeight: 3, // 线宽
        strokeOpacity: 0.5 // 线透明度
    });
}

// 创建飞机标记
function createPlaneMarker(map, position, icon) {
    return new AMap.Marker({
        map: map,
        position: position,
        icon: new AMap.Icon({
            size: new AMap.Size(30, 30), // 图标大小
            image: icon, // 图标路径
            imageSize: new AMap.Size(30, 30) // 图标实际大小
        }),
        offset: new AMap.Pixel(-15, -15), // 图标偏移量
        //autoRotation: true, // 随着路径旋转
        angle: -270 // 图标初始旋转角度
    });
}

// 飞机图标路径（请替换为实际图标路径）
var planeIcon = '../css/plane.png';

// 开始地点名称到坐标的转换
//convertLocationsToCoordinates(locationData);
/*const plan = {
    "plan_state": 0,
    "route": [
        { keyword:"天津市"},
        { keyword:"广州市"},
        { keyword:"武汉市"},
        { keyword:"深圳市"},
        { keyword:"成都市"},
        { keyword:"合肥市"},
        { keyword:"上海市"},
        { keyword:"南京市"},
        
    ],
    "recharge_number": 2,
    "recharge_route": [
        [
            { keyword:"北京市"},
            { keyword:"合肥市"}
        ],
        [
            { keyword:"杭州市"},
            { keyword:"广州市"}
        ]
    ]
};*/
var plan=JSON.parse(localStorage.getItem("searchData"));
console.log(plan);
function executeSearch(plan) {
    if (plan.plan_state === 0) {
        doSearch(plan.route);
    } else if (plan.plan_state === 1) {
        convertLocationsToCoordinates(plan.route);
    } else {
        console.log("Invalid plan state.");
    }

    // 如果存在recharge_route字段，则遍历并调用doSearch
    if (plan.recharge_route && plan.recharge_route.length > 0) {
        plan.recharge_route.forEach(recharge => {
            doSearch(recharge);
        });
    }
   // localStorage.removeItem("searchData");
}
executeSearch(plan);







